package com.atguigu.gulimail.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimail.product.controller")
public class ExceptionHandler {
    @org.springframework.web.bind.annotation.ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        log.error("错误类型：{}", throwable.getClass());
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getValue(),
                BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(value =
            MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException e) {
        final BindingResult result = e.getBindingResult();
        if (result.hasErrors()) {
            Map<String, String> errMap = new HashMap<>();
            result.getFieldErrors().forEach(item -> {
                errMap.put(item.getField(), item.getDefaultMessage());
            });
            return R.error(BizCodeEnum.VALID_PARAM_EXCEPTION.getValue(),
                    BizCodeEnum.VALID_PARAM_EXCEPTION.getMsg()).put("data", errMap);
        }
        return null;
    }


}
